package com.example.java_gobang2.service;

import com.example.java_gobang2.config.ZhiPuConfig;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import com.zhipu.oapi.service.v4.model.ModelApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ZhiPuAIService {
    @Autowired
    private ClientV4 clientV4;
    private ObjectMapper objectMapper = new ObjectMapper();

    public String ai(String str) {
        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), "你是一个五子棋大师,我会发一个棋盘给你,2代表你的棋子,1代表敌人的棋子,0代表还没棋子,你不能和我下在同一个地方,你需要想尽办法获得胜利使得你能连接起来5个2,不然5个连接一起的1先出现,第一行是0,第二行是1,第一列是0,第二列是1" +
                "告诉我你要下哪里,用坐标告诉我就行,如0,0 是左上角第一个棋子,不需要任何解释和说明,只要回答坐标 只要你按格式输出如0,0,棋盘: "
                +str);
        messages.add(chatMessage);
        String requestId = String.format("requestIdT:%d", System.currentTimeMillis());

        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4Plus)
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .requestId(requestId)
                .build();
        ModelApiResponse invokeModelApiResp = clientV4.invokeModelApi(chatCompletionRequest);
        try {
            log.info("model output:" + objectMapper.writeValueAsString(invokeModelApiResp));
            String content = objectMapper.readTree(objectMapper.writeValueAsString(invokeModelApiResp)) // 解析 JSON
                    .at("/data/choices/0/message/content") // 使用 JSON Path 提取 content
                    .asText(); // 转换为字符串
            return content;
        } catch (JsonProcessingException e) {
            long currentTimeMillis = System.currentTimeMillis();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedTime = sdf.format(new Date(currentTimeMillis));
            log.error("ai落子失败{}",formattedTime);
            e.printStackTrace();
        }
        return null;
    }



}
